package com.sike.netty.im.server.handler;

import com.sike.netty.im.common.command.CreateGroupRequestCommand;
import com.sike.netty.im.common.command.CreateGroupResponseCommand;
import com.sike.netty.im.common.command.Message;
import com.sike.netty.im.common.command.MessageBuilder;
import com.sike.netty.im.server.service.BeanFactory;
import com.sike.netty.im.server.service.GroupService;
import com.sike.netty.im.server.service.SessionService;
import com.sike.netty.im.server.service.UserInfoCache;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import lombok.extern.slf4j.Slf4j;

/**
 * 创建组请求 Handler
 *
 * @author chenssy
 * @date 2023/09/18
 */
@Slf4j
public class CreateGroupRequestHandler extends SimpleChannelInboundHandler<CreateGroupRequestCommand> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CreateGroupRequestCommand msg) throws Exception {
        // 创建群聊
        GroupService groupService = (GroupService) BeanFactory.getServiceBean(GroupService.class);
        String groupId = groupService.createGroup(msg);

        // 通知群成员
        SessionService sessionService = (SessionService) BeanFactory.getServiceBean(SessionService.class);
        // 创建一个 Channel 分组
        ChannelGroup channelGroup = new DefaultChannelGroup(ctx.executor());
        for (String userName : msg.getGroupMemberList()) {
            // 获取在线的连接
            Channel channel = sessionService.getChannelByUserId(UserInfoCache.getUserInfoByUserName(userName).getUserId());
            if (channel != null) {
                channelGroup.add(channel);
            }
        }

        CreateGroupResponseCommand responseCommand = new CreateGroupResponseCommand();
        responseCommand.setGroupId(groupId);
        responseCommand.setGroupName(msg.getGroupName());
        responseCommand.setGroupMemberList(msg.getGroupMemberList());
        Message message = MessageBuilder.buildMessage(responseCommand,null,null);
        channelGroup.writeAndFlush(message);

        log.info("[{}]群已创建完毕，群id:{},群成员:{}",msg.getGroupName(), groupService,String.join(",",msg.getGroupMemberList()));
    }
}
